package dao

import (
	"fmt"
	"sync"

	"gorm.io/gorm"
	"github.com/spf13/viper"
)

var globalDB *gorm.DB
var userDao  *UserDao
var once     sync.Once
var userDaoOnce sync.Once

func GetGlobalDB() *gorm.DB {
	if globalDB == nil {
		once.Do(func() {
			prefix := "storage."
			diverName := viper.GetString(prefix + "driverName")
			host := viper.GetString(prefix + "host")
			port := viper.GetString(prefix + "port")
			name := viper.GetString(prefix + "username")
			pwd := viper.GetString(prefix + "password")
			dbName := viper.GetString(prefix + "database")
			charset := viper.GetString(prefix + "charset")
			db, err := OpenDbWithDsn(diverName, fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local", name, pwd, host, port, dbName, charset))
			if err != nil {
				panic(err)
			}
			globalDB = db
		})
	}
	return globalDB
}

func InitDaoInstance() {
	if userDao == nil {
		userDaoOnce.Do(func ()  {
			userDao = NewUserDao(GetGlobalDB())
		})
	}
}

func GetUserDaoInstance() *UserDao {
	if userDao == nil {
		userDaoOnce.Do(func ()  {
			userDao = NewUserDao(GetGlobalDB())
		})
	}
	return userDao
}
